const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/API/User/index');
const companyRouter = require('./routes/API/Company/index');
const postRouter = require('./routes/API/Post/index');
const postTypeRouter = require('./routes/API/PostType/index');
const publisherRouter = require('./routes/API/Publisher/index');
const UploadRouter = require('./routes/API/Upload/index');


var cors = require('cors');
const app = express();

//设置跨域访问
app.use(cors({
  origin:['http://localhost:3001'],  //指定接收的地址
  methods:['GET','POST'],  //指定接收的请求类型
  alloweHeaders:['Content-Type','Authorization']  //指定header
}))

// 原生写法 得搭配路由 在app.use(router);前面
// app.all('*', function(req, res, next) {
//   res.header("Access-Control-Allow-Origin", "*");
//   res.header("Access-Control-Allow-Headers", "X-Requested-With");
//   res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
//   res.header("X-Powered-By",' 3.2.1');
//   res.header("Content-Type", "application/json;charset=utf-8");
//   if (req.method == 'OPTIONS') {
//     //让options请求快速返回
//     res.sendStatus(200);
//   } else {
//     next();
//   }
// })

// 解析静态文件
app.use('/public',express.static('public'));



// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/user', usersRouter);
app.use('/company', companyRouter);
app.use('/post', postRouter);
app.use('/postType', postTypeRouter);
app.use('/publisher', publisherRouter);
app.use('/Upload', UploadRouter);



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
